import 'package:flutter/material.dart';
import 'package:lx_widgets_library/config.dart';
import 'package:webview_flutter/webview_flutter.dart';

/*  在其他地方调用
  Navigator.push(
    context,
    MaterialPageRoute(
      builder: (context) => CustomWebView(
        url: 'https://www.example.com',
        title: '示例网页',
      ),
    ),
  );
*/

/// 自定义 WebView
class CustomWebView extends StatefulWidget {
  final String url;
  final String title;
  final bool showFloatingActionButton;

  const CustomWebView({
    super.key,
    required this.url,
    required this.title,
    this.showFloatingActionButton = false,
  });

  @override
  State<CustomWebView> createState() => _CustomWebViewState();
}

class _CustomWebViewState extends State<CustomWebView> {
  late final CustomWebViewController _webViewController;
  String _currentTitle = '';
  double _loadingProgress = 0;

  @override
  void initState() {
    super.initState();
    _currentTitle = widget.title;
    _webViewController = CustomWebViewController(
      initialUrl: widget.url,
      initialTitle: widget.title,
      onTitleChanged: (title) => setState(() => _currentTitle = title),
      onProgressChanged: (progress) =>
          setState(() => _loadingProgress = progress),
      onPageFinished: () => debugPrint('Page loaded: ${widget.url}'),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        title: Text(_currentTitle),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _webViewController.reload,
          ),
        ],
      ),
      body: Stack(
        children: [
          WebViewWidget(controller: _webViewController.controller),
          if (_loadingProgress < 1)
            LinearProgressIndicator(
              value: _loadingProgress,
              backgroundColor: Colors.transparent,
              valueColor: AlwaysStoppedAnimation<Color>(
                  LxWidgetsLibraryService.to.colorType.color6.withOpacity(0.8)),
              minHeight: 3,
            ),
        ],
      ),
      floatingActionButton: Visibility(
        visible: widget.showFloatingActionButton,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            FloatingActionButton(
              heroTag: 'back',
              mini: true,
              onPressed: () async {
                if (await _webViewController.canGoBack()) {
                  await _webViewController.goBack();
                }
              },
              child: const Icon(Icons.arrow_back),
            ),
            const SizedBox(width: 10),
            FloatingActionButton(
              heroTag: 'forward',
              mini: true,
              onPressed: () async {
                if (await _webViewController.canGoForward()) {
                  await _webViewController.goForward();
                }
              },
              child: const Icon(Icons.arrow_forward),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _webViewController.clearCache(); // 可选：关闭时清除缓存
    super.dispose();
  }
}

/// 自定义 WebView 控制器
class CustomWebViewController {
  late final WebViewController _controller;
  final String initialUrl;
  final String initialTitle;
  final ValueChanged<String>? onTitleChanged;
  final ValueChanged<double>? onProgressChanged;
  final VoidCallback? onPageStarted;
  final VoidCallback? onPageFinished;

  CustomWebViewController({
    required this.initialUrl,
    required this.initialTitle,
    this.onTitleChanged,
    this.onProgressChanged,
    this.onPageStarted,
    this.onPageFinished,
  }) {
    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (progress) => onProgressChanged?.call(progress / 100),
          onPageStarted: (url) => onPageStarted?.call(),
          onPageFinished: (url) async {
            final title = await _controller.getTitle() ?? initialTitle;
            onTitleChanged?.call(title);
            onPageFinished?.call();
          },
          onNavigationRequest: (request) {
            // 允许所有导航
            return NavigationDecision.navigate;
          },
        ),
      )
      ..loadRequest(Uri.parse(initialUrl));
  }

  // 获取底层 WebViewController
  WebViewController get controller => _controller;

  // 导航方法
  Future<void> loadUrl(String url) => _controller.loadRequest(Uri.parse(url));
  Future<void> reload() => _controller.reload();
  Future<void> goBack() => _controller.goBack();
  Future<void> goForward() => _controller.goForward();
  Future<bool> canGoBack() => _controller.canGoBack();
  Future<bool> canGoForward() => _controller.canGoForward();

  // 执行 JavaScript
  Future<String> evaluateJavaScript(String js) async {
    try {
      return await _controller.runJavaScriptReturningResult(js) as String;
    } catch (e) {
      return 'Error: $e';
    }
  }

  // 清除缓存
  Future<void> clearCache() async {
    await _controller.clearLocalStorage();
    await WebViewCookieManager().clearCookies();
  }
}
